package com.github.cyf.webSocket;

import com.github.cyf.service.RecordService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author chenyifan
 * @create 2025-03-17 10:55
 */
@Component
@Slf4j
@Service
// 将目前的类定义成一个 websocket 服务器端，客户端可以通过这个 URL 来连接到 WebSocket 服务器端
@ServerEndpoint("/api/websocket/{sid}")
public class WebSocketServer {

    /**
     * 存放每个客户端对应的 Session 对象
     */
    private static final Map<String, WebSocketServer> WEB_SOCKET_MAP = new ConcurrentHashMap<>();

    /**
     * 当前在线连接数
     */
    private static int onlineCount = 0;

    private Session session;

    private String sid;

    public static RecordService recordService;

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("sid") String sid) {
        this.session = session;
        this.sid = sid;
        WEB_SOCKET_MAP.put(sid, this);
        addOnlineCount();
        sendMessage("conn_success");
//        recordService.record("连接成功");
        log.info("有新窗口开始监听:" + sid + ",当前在线人数为:" + getOnlineCount());
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(@PathParam(value = "sid") String sid) {
        WEB_SOCKET_MAP.remove(sid);
        subOnlineCount();
        log.info("释放的sid = {}, 当前在线人数为{}", sid, onlineCount);
    }


    /**
     * 收到客户端消息后调用的方法
     * @Param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("收到来自客户端 {} 的信息:{}", sid, message);
    }

    /**
     * 发生错误回调
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("客户端 {} 发生错误", sid, error);
    }

    public static void sendMessageToUser(String sid, String message) {
        WebSocketServer socketServer = WEB_SOCKET_MAP.get(sid);
        if (socketServer != null) {
            socketServer.sendMessage(message);
        } else {
            log.error("用户 {} 不在线", sid);
        }
    }

    /**
     * 群发自定义消息
     */
    public static void sendMessageToAll(String message) {
        for (WebSocketServer socketServer : WEB_SOCKET_MAP.values()) {
            socketServer.sendMessage(message);
        }
    }

    /**
     * 服务器推送消息给指定用户
     * @param message 消息
     */
    public void sendMessage(String message) {
        try {
            this.session.getBasicRemote().sendText(message);
        } catch (IOException e) {
            throw new RuntimeException("发送消息失败", e);
        }
    }

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        WebSocketServer.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        WebSocketServer.onlineCount--;
    }

    public static Map<String, WebSocketServer> getWebSocketMap() {
        return WEB_SOCKET_MAP;
    }
}